package com.code.coinprice.handlers.client;

import com.code.coinprice.utils.ByteUtils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

public class ZbWebSocketClient extends WebSocketClient {

    private static final Logger log = LoggerFactory.getLogger(ZbWebSocketClient.class);

    public static BlockingQueue<String> zbMarketQueue = new LinkedBlockingDeque<>(1);

    public ZbWebSocketClient(URI serverUri) {
        super(serverUri);
    }

    public ZbWebSocketClient(URI serverUri, Draft protocolDraft) {
        super(serverUri, protocolDraft);
    }

    public ZbWebSocketClient(URI serverUri, Draft protocolDraft, Map<String, String> httpHeaders, int connectTimeout) {
        super(serverUri, protocolDraft, httpHeaders, connectTimeout);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        log.info("[zb's websocket] 连接成功");
        //devOrder.subscribeDev("33255773800487108280");
    }

    @Override
    public void onMessage(String message) {
        // log.info("[exGroupMarket's websocket] 收到字符串类型的消息={}", message);
        if (!StringUtils.isEmpty(message) && !message.contains("ping")) {
            zbMarketQueue.offer(message);
        }

    }

    @Override
    public void onMessage(ByteBuffer bytes) {
        log.info("[zb's websocket] 收到ByteBuffer类型的消息={}", ByteUtils.getString(bytes));

    }

    @Override
    public void onClose(int i, String s, boolean b) {
        log.info("[zb's websocket] 退出连接");
    }

    @Override
    public void onError(Exception e) {
        e.printStackTrace();
        log.info("[zb's websocket] 连接错误={}", e.getMessage());
    }
}
